import React, { useState, useEffect, useRef } from 'react';
import './style.css';
import Main from './components/Layout';
import TaskReport from './reports/task_report';
import fetch from 'API/fetch';
// import fetch from 'API/fetch';
// import { getParams, flatToTree } from './common/constant';
import { ApolloProvider } from '@apollo/client';
import { getParams } from './helpers/getUrlParams';
import Notification from '@knownsec/react-component/dist/Notification';
import locale from "antd/es/locale/zh_CN.js";
import { ConfigProvider } from 'antd';
import cookie from 'react-cookies'
import { HashRouter, Switch, Route, BrowserRouter, Link } from 'react-router-dom';

if (!sessionStorage.resD) {
	sessionStorage.setItem('resD', JSON.stringify({ feature: {}, balance: {} }));
}
if (!sessionStorage.aviliableNode) {
	sessionStorage.setItem('aviliableNode', JSON.stringify(null));
}
export const getResD = async () => {
	const resD = await fetch('/api/v2/users/balance/get', {
		method: 'GET',
	});
	if (resD.code === 200) {
		sessionStorage.setItem('resD', JSON.stringify(resD.results));
	}
};
export const getNodeList = async () => {
	const resD = await fetch('/api/v2/tasks/available/node', {
		method: 'GET',
	});
	if (resD.code === 200) {
		sessionStorage.setItem('aviliableNode', JSON.stringify(resD.data));
	}
};

const App = () => {
	const isReport = window.location?.hash?.indexOf('/report/task_report') > -1
	const [ticket, setTicket] = useState(getParams()?.ticket || "");
	const [balance, setBalance] = useState(null)
 	const getResD_ = async () => {
		const resD = await fetch('/api/v2/users/balance/get', {
			method: 'GET',
		});
		if (resD.code === 200) {
			setBalance(resD.results)
			sessionStorage.setItem('resD', JSON.stringify(resD.results));
		}
	}
	const {
		app: { ViewWrapper, apollo },
	} = window.kuiper;
	useEffect(() => {
		if (ticket && ticket !== getParams()?.ticket) {
			fetch('/api/v2/users/login?service=' + window.location.origin + '/&ticket=' + ticket, { method: 'GET' }).then((res) => {
				const cookieSetup = {
					path: '/',
					domain: window.location.hostname.includes('console.') ? '.scanv.com' : window.location.hostname,
				}
				cookie.save("token", res.data.token, cookieSetup);
				window.location.href = "/";
			}).catch(res => {
				console.log(res.message)
			});
		} else {
			getResD_()
			getNodeList()
		}
	}, [isReport])
	return (
		<ApolloProvider client={apollo}>
			<ConfigProvider locale={locale}>
				<HashRouter>
					<Switch>
						{ticket ? (
							<></>
						) : (
							<Route
								exact
								path="*"
								render={() => (
									<div className="App">
										{isReport ? <TaskReport /> : (balance && <Main balance={balance} />)}
									</div>
								)}
							/>
						)}
					</Switch>
				</HashRouter>
			</ConfigProvider>
		</ApolloProvider>
	);
};
export default App;
